<template>
    <section>
        <div class="panel">
            <div class="panel-head">
                <strong><i class="el-icon-date"/><span class="title">晒单数据</span></strong>
            </div>
            <div class="body-content">
                <el-form :inline="true" size='small'>
                    <el-form-item label="">
                        <el-button type="primary" @click="addeditDailog('add')" size='small'>新增</el-button>                        
                    </el-form-item>
                </el-form>
                <!--表格数据-->
                <el-table :data="tableData" v-loading="listLoading" element-loading-text="拼命加载中" border>
                    <el-table-column type='index' width='50' label="序号"/>
                    <el-table-column prop="perNo" label="期号"/>
                    <el-table-column prop="nickName" label="昵称"/>
                    <el-table-column label="头像">
                        <template slot-scope="scope">
                            <img :src="scope.row.headImg" alt="logo" style="width: 50px;height: 50px;margin: 0 auto;"/>
                        </template>
                    </el-table-column>
                    <el-table-column label="商品图片">
                        <template slot-scope="scope">
                            <img :src="scope.row.goodImg" alt="logo" style="width: 50px;height: 50px;margin: 0 auto;"/>
                        </template>
                    </el-table-column>
                    <el-table-column prop="title" label="商品标题" width='100'/>
                    <el-table-column prop="price" label="商品价格" width='100'/>
                    <el-table-column prop="userNumber" label="用户中奖号码" width='100'/>
                    <el-table-column prop="content" label="分享内容" width='100'/>
                    <el-table-column label="操作" width="90">
                        <template slot-scope="scope">
                            <el-button type="primary" size="mini" @click="addeditDailog('edit',scope.row)">编辑</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <!-- 分页 -->
                <div class="paginationMargin">
                    <el-pagination layout="prev, pager, next" background :current-page='currentPage' :page-count='pageCount' @current-change="handleCurrentChange"/>
                </div>
                <!-- 弹窗 -->
                <el-dialog :title="dialogTitle" :close-on-click-modal='false' :visible.sync="dialogFormVisible" width="50%" @close="closeDailog">
                    <el-form label-width="180px">
                        <el-form-item label="期号:">
                            <el-input v-model.trim="dailogFrom.perNo" placeholder="期号" size='small' style="width:200px;"/>
                        </el-form-item>
                        <el-form-item label="昵称:">
                            <el-input v-model.trim="dailogFrom.nickName" placeholder="昵称" size='small' style="width:200px;"/>
                        </el-form-item>
                        <el-form-item label="头像:">
                            <el-form :inline="true">
                                <el-form-item>
                                    <el-input v-model.trim="dailogFrom.headImg" style="width:280px;" size="small"/>
                                </el-form-item>
                                <el-form-item>
                                    <el-upload class="upload-demo" with-credentials name="file" ref="upload" :action="uploadURL" :on-exceed="handleExceed" :on-remove="handleRemove" :on-success='handleSuccess' :file-list="fileList" :limit="1" :before-upload="beforeAvatarUpload">
                                        <el-button size="small" type="primary">点击上传</el-button>
                                    </el-upload>
                                </el-form-item>
                            </el-form>
                        </el-form-item>
                        <el-form-item label="显示的图片:">
                            <el-upload
                                class="upload-demo-list"
                                with-credentials 
                                name="file" 
                                :action="uploadURL"
                                list-type="picture-card"
                                :file-list="fileListShowImgs"
                                :on-remove="handleRemoveCard"
                                :on-exceed="handleExceedCard" 
                                :on-success='handleSuccessCard' 
                                :limit="6" 
                                :before-upload="beforeAvatarUpload">
                                <i class="el-icon-plus"></i>
                            </el-upload>
                        </el-form-item>
                        <el-form-item label="选择商品:">
                            <el-autocomplete
                                popper-class="my-autocomplete"
                                v-model="goodsName"
                                :fetch-suggestions="querySearch"
                                placeholder="请输入商品名称"
                                size='small' 
                                style="width:300px;"
                                @select="handleSelect">
                                <template slot-scope="props">
                                    <div class="name">{{ props.item.title }}</div>
                                    <div class="addr">价格：{{ props.item.price }}</div>
                                    <img :src="props.item.goodImg" alt="logo" style="width: 50px;height: 50px;margin: 0 auto;"/>
                                </template>
                            </el-autocomplete>
                        </el-form-item>
                        <el-form-item label="分享内容:">
                            <el-input type="textarea" :rows="2" v-model.trim="dailogFrom.content" placeholder="分享内容" size='small' style="width: 300px"/>
                        </el-form-item>
                        <el-form-item label="用户中奖号码:">
                            <el-input v-model.trim="dailogFrom.userNumber" placeholder="用户中奖号码" size='small' style="width:200px;"/>
                        </el-form-item>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button size="small" @click="dialogFormVisible = false">取 消</el-button>
                        <el-button size="small" type="primary" @click="confirm">确 定</el-button>
                    </div>
                </el-dialog>
            </div>
        </div>
    </section>
</template>
<script>
import * as api from "../../api/api";
// import { PAGE_SIZE } from "@/config";

export default {
    data() {
        return {
            listLoading: false, //加载中
            searchObj: {
                name: "",
            }, //查询参数
            tableData: [], //查询列表
            currentPage: 1, // 当前页数
            pageCount: 1, // 总页数
            pageSize: 20,

            dialogTitle: "", // 弹窗标题
            dialogType: "", // 弹窗类型

            dialogVisible: false,
            dialogFormVisible: false,
            formLabelWidth: "120px",
            dailogFrom: {
                headImg: ''
            },

            uploadURL: `${api.uploadFileURL}`,
            fileList: [],

            goodsName: '',
            // 商品列表
            goodsList: [],
            // 展示的图片list
            fileListShowImgs: [],
        };
    },
    methods: {
        // 点击查询
        onSubmit() {
            this.currentPage = 1; // 将页码置为第一页
            // 查询数据列表
            this.getDataList();
        },
        // 分页点击方法
        handleCurrentChange(val) {
            this.currentPage = val;
            // 查询数据列表
            this.getDataList();
        },
        // 查询数据列表
        getDataList() {
            this.listLoading = true;
            api.showAllWinInfos({
                ...this.searchObj,
                pageNum: this.currentPage,
                pageSize: this.pageSize,
            })
                .then(res => {
                    this.listLoading = false;
                    const list = res.data.content;
                    this.tableData = list;
                    this.pageCount = res.data.totalPages
                })
                .catch(() => {
                    this.listLoading = false;
                });
        },
        // 新增/编辑 弹窗
        addeditDailog(type, rowData) {
            this.dialogType = type;
            if (type == 'edit') {
                this.dailogFrom = { ...rowData };
                this.dailogFrom.goodsId = rowData.goodsId;
                const showImgs = rowData.showImgs;
                // 显示商品图片
                if (showImgs) {
                    const showImgsArr = showImgs.split(',');
                    const fileListShowImgs = showImgsArr.map(o => {
                        return { name: '', url: o }
                    });
                    console.log(fileListShowImgs, 'fileListShowImgs');
                    this.fileListShowImgs = fileListShowImgs;
                }
                this.goodsName = rowData.title;
            }
            this.dialogFormVisible = true;
        },
        // 关闭弹窗 输入框数据清空
        closeDailog() {
            this.dailogFrom = {headImg: ''};
            this.fileList = [];
            this.fileListShowImgs= [];
            this.goodsName = '';
        },
        // 新增/编辑 确定
        confirm() {
            if (!this.dailogFrom.perNo) {
                this.$message.error("请输入期号!");
                return false;
            }
            if (!this.dailogFrom.nickName) {
                this.$message.error("请输入昵称!");
                return false;
            }
            if (!this.dailogFrom.headImg) {
                this.$message.error("请上传头像!");
                return false;
            }
            if (!this.fileListShowImgs.length) {
                this.$message.error("请上传显示图片!");
                return false;
            }
            if (!this.dailogFrom.goodsId) {
                this.$message.error("请选择商品!");
                return false;
            }
            if (!this.dailogFrom.content) {
                this.$message.error("请输入分享内容!");
                return false;
            }
            if (!this.dailogFrom.userNumber) {
                this.$message.error("请输入用户中奖号码!");
                return false;
            }
            const showImgsArr = this.fileListShowImgs.map(o => o.url);
            this.dailogFrom.showImgs = showImgsArr.toString();
            console.log(this.dailogFrom);
            api.addWinInfos(this.dailogFrom)
                .then(res => {
                    console.log(res, 'res>>>>');
                    this.$message.success(`${this.dialogType === "add" ? `添加` : `修改`}成功!`);
                    // 获取数据列表
                    this.getDataList();
                    this.dialogFormVisible = false;
                })
        },
        // 超出上传限制提示
        handleExceed() {
            this.$message.warning("当前限制只能上传 1 个文件");
        },
        // 文件移除事件
        handleRemove() {
            this.fileList = [];
            this.dailogFrom.headImg = "";
        },
        // 上传成功
        handleSuccess(res) {
            console.log(res);
            if (res.code == 200) {
                this.$message.success("上传成功！");
                this.dailogFrom.headImg = res.data;
            } else {
                this.$message.error(res.message);
            }
        },
        handleExceedCard(){
            this.$message.warning("当前限制只能上传 6 个文件");
        },
        handleRemoveCard(file, fileList){
            this.fileListShowImgs= fileList;
        },
        // 上传成功
        handleSuccessCard(res) {
            console.log(res);
            if (res.code == 200) {
                this.$message.success("上传成功！");
                this.fileListShowImgs.push({ name: '', url: res.data})
            } else {
                this.$message.error(res.message);
            }
        },
        // 文件大小 文件名判断
        beforeAvatarUpload(file) {
            const fileName = file.name;
            const index = fileName.lastIndexOf(".");
            const fileFormat = fileName.substring(index + 1, fileName.length);
            const isName =
                fileFormat === "png" ||
                fileFormat === "jpg" ||
                fileFormat === "jpeg";
            const isLt800KB = file.size / 1024 < 800;
            if (!isName) {
                this.$message.error("上传文件只能是 png/jpg/jpeg 格式!");
                this.fileList = [];
            }
            if (!isLt800KB) {
                this.$message.error("上传文件大小不能超过 800KB!");
                this.fileList = [];
            }
            return isName && isLt800KB;
        },
        // 查询数据列表
        getGoodsList() {
            api.randGoods({
                pageNum: 1,
                pageSize: 100,
            })
                .then(res => {
                    const list = res.data.content;
                    this.goodsList = list;
                })
                .catch(() => {
                });
        },
        querySearch(queryString, cb) {
            var restaurants = this.goodsList;
            var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
            // 调用 callback 返回建议列表的数据
            cb(results);
        },
        createFilter(queryString) {
            return (restaurant) => {
                return (restaurant.title.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
            };
        },
        handleSelect(item) {
            console.log(item, 'handleSelect');
            this.goodsName = item.title;
            this.dailogFrom.goodsId = item.id;
        },
    },
    mounted() {
        // 查询数据列表
        this.getDataList();
        this.getGoodsList();
    }
};
</script>

<style lang="scss">
.my-autocomplete {
  li {
    line-height: normal;
    padding: 7px;

    .name {
      text-overflow: ellipsis;
      overflow: hidden;
    }
    .addr {
      font-size: 12px;
      color: #b4b4b4;
    }

    .highlighted .addr {
      color: #ddd;
    }
  }
}
</style>
